/**
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 **/
import {
	defineStore
} from 'pinia';
import {
	$Api
} from '@/api';
import {
	maskPhoneNumber
} from '@/utils/utools.js'
import {
	chooseLocation
} from '@/utils/chooseLocation';
export const userInfoStore = defineStore('userInfo', {
	state: () => ({
		userInfo: null,
		addressInfo: null,
		accountInfo: null,
		openId: "",
		inviteInfo: null, //受邀请的推广码
		storeInfo: null, //商户信息
		storeShopInfo: null, //商家的门店info
		level_info: null, //会员等级信息
		next_level_info: null, //下一等级信息
		assistantOrderInfo: null
	}),
	getters: {},
	actions: {
		async getUserInfo() { //获取用户信息
			const res = await $Api.user.getUserInfo();
			// console.log('getUserInfo', res);
			if (res.code == '1') {
				const {
					userinfo
				} = res.data;
				if (userinfo.got_open_id !== 1) { //未获取openid,获取openid
					this.getOpenId();
				}
				const provinceName = userinfo.provinceName || '';
				const cityName = userinfo.cityName ? '-' + userinfo.cityName : '';
				const districtName = userinfo.districtName ? '-' + userinfo.districtName : '';
				let newMobile = '';
				if (userinfo.mobile) {
					newMobile = maskPhoneNumber(userinfo.mobile);
				}
				if (userinfo.level && this.level_info) {
					let list = this.level_info?.value || [];
					let nextLevelInfo = null;
					let currentLevelInfo = list.find(val => val.vl_id == userinfo?.level);
					if (currentLevelInfo) { //是否有当前等级
						let newlist = [];
						newlist = list.sort((a, b) => a.all_count - b.all_count)
						//获取下一等级信息
						let nextIndex = newlist.findIndex(val => val.vl_id == userinfo.level);
						if (nextIndex !== -1 && nextIndex < newlist.length - 1) {
							nextLevelInfo = newlist[nextIndex + 1];
						} else {
							nextLevelInfo = {
								all_count: 9999,
								vl_name: '最高等级'
							}
						}
					}
					this.next_level_info = nextLevelInfo
				}
				this.userInfo = {
					...userinfo,
					newMobile,
					area: provinceName + cityName + districtName
				};
			} else {
				uni.hideLoading();
				uni.$u.toast(res.msg)
			}
		},
		async getAccount() { //获取金额积分等信息
			const res = await $Api.user.getAccount();
			if (res.code == '1') {
				this.accountInfo = res.data;
			} else {
				uni.hideLoading();
				uni.$u.toast(res.msg)
			}
		},
		async getMerchantInfo() {
			const res = await $Api.store.getMerchantInfo();
			if (res.code == 1) {
				let imageList = [];
				if (res.data.banner_image) {
					if (typeof res.data.banner_image === 'string') {
						imageList = res.data.banner_image.split(',');
					} else if (Array.isArray(res.data.banner_image)) {
						res.data.banner_image.forEach(item => {
							imageList.push(item.url);
						})
					}
				}
				this.storeInfo = {
					...res.data,
					imageList
				};
			} else {
				uni.$u.toast(res.msg);
			}
		},
		async getOpenId() {
			uni.login({
				provider: 'weixin', //使用微信code
				success: async (loginRes) => {
					// console.log(loginRes);
					if (loginRes.code) {
						const res = await $Api.login.getOpenId({
							code: loginRes.code
						})
						if (res.code == '1') {

						} else {
							uni.$u.toast(res.msg);
						}
					}

				}
			});
		},
		async getLevelList() { //获取等级列表
			const res = await $Api.user.getLevelList();
			if (res.code == 1) {
				let tabList = [{
					name: '全部',
					label: 0
				}]
				const {
					list
				} = res.data;
				list.forEach(val => {
					tabList.push({
						name: val.vip_name,
						label: val.vl_id
					})
				});
				let nextLevelInfo = null;
				let currentLevelInfo = list.find(val => val.vl_id == this.userInfo?.level);
				if (currentLevelInfo) { //是否有当前等级
					let newlist = [];
					newlist = list.sort((a, b) => a.all_count - b.all_count)
					//获取下一等级信息
					let nextIndex = newlist.findIndex(val => val.vl_id == this.userInfo.level);
					if (nextIndex !== -1 && nextIndex < newlist.length - 1) {
						nextLevelInfo = newlist[nextIndex + 1];
					} else {
						nextLevelInfo = {
							all_count: 9999,
							vl_name: '最高等级'
						}
					}
				}
				//设置当前用户等级;

				this.level_info = {
					name: "level_info",
					title: "等级信息",
					value: list,
					tabList
				}
				this.next_level_info = nextLevelInfo
			} else {
				uni.$u.toast(res.msg)
			}

		},
		setInviteInfo(code, type) {
			this.inviteInfo = {
				code,
				type
			}
		},
		setAssistantOrderInfo(info) {
			this.assistantOrderInfo = info;
		},
		removeUserinfo() {
			this.userInfo = null;
		},
		async setAddressInfo(info) {
			const res = await chooseLocation(this.addressInfo?.latitude, this.addressInfo?.longitude);
			if (res.districtInfo) {
				this.addressInfo = res;
			}

		},
		setStoreShop(info) { //设置当前商家门店信息
			this.storeShopInfo = info;
		},
		setUserInfo(info) {
			if (info) {
				if (info.got_open_id !== 1) { //未获取openid,获取openid
					this.getOpenId();
				}
				const provinceName = info.provinceName || '';
				const cityName = info.cityName ? '-' + info.cityName : '';
				const districtName = info.districtName ? '-' + info.districtName : '';
				let newMobile = '';
				if (info.mobile) {
					newMobile = maskPhoneNumber(info.mobile);
				}
				if (info.level && this.level_info) {
					let list = this.level_info?.value || [];
					let nextLevelInfo = null;
					let currentLevelInfo = list.find(val => val.vl_id == info?.level);
					if (currentLevelInfo) { //是否有当前等级
						let newlist = [];
						newlist = list.sort((a, b) => a.all_count - b.all_count)
						//获取下一等级信息
						let nextIndex = newlist.findIndex(val => val.vl_id == info.level);
						if (nextIndex !== -1 && nextIndex < newlist.length - 1) {
							nextLevelInfo = newlist[nextIndex + 1];
						} else {
							nextLevelInfo = {
								all_count: 9999,
								vl_name: '最高等级'
							}
						}
					}
					this.next_level_info = nextLevelInfo
				}
				this.userInfo = {
					...info,
					newMobile,
					area: provinceName + cityName + districtName
				};
				return;
			}
			this.userInfo = info;
		},
		setAccountInfo(info) {
			this.accountInfo = info;
		},
		changeAccountInfo(key, value) { //设置金额积分等信息
			if (key && value && this.accountInfo[key] && this.accountInfo[key] > value) {
				this.accountInfo[key] = this.accountInfo[key] - value;
			}
		},
		async setUserAddress(data) { //设置用户信息得地址
			let user_token = uni.getStorageSync('user_token');
			if (!user_token) return;
			if (!data) return;
			if (!this.userInfo) return;
			if (this.userInfo.city && this.userInfo.city != 0) return;
			const res = await $Api.user.setAddress({
				lat: data.lat,
				lng: data.lng,
			})
			if (res.code === 1) {
				console.log('设置用户地址成功')
				this.userInfo.city = res.data.city;
				this.userInfo.province = res.data.province;
				this.userInfo.district = res.data.district;
			}

		},

	},
	persist: {
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, value) {
				return uni.setStorageSync(key, value)
			},
		},
	},
})